import 'package:flutter/material.dart';
import 'package:test_for_pageview_lifecycle/video_urls.dart';
import 'package:video_player/video_player.dart';
import 'package:visibility_detector/visibility_detector.dart';

class PageTestItem extends StatefulWidget {
  const PageTestItem({
    Key? key,
    required this.index,
  }) : super(key: key);
  final int index;

  @override
  State<PageTestItem> createState() => _PageTestItemState();
}

class _PageTestItemState extends State<PageTestItem> {
  bool isVisiable = false;
  late VideoPlayerController _controller;

  @override
  void initState() {
    super.initState();
    _controller = VideoPlayerController.network(videoUrls[widget.index])
      ..initialize().then((_) {
        setState(() {});
      });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return VisibilityDetector(
      key: Key('${widget.index} item'),
      onVisibilityChanged: (VisibilityInfo info) {
        if (!mounted) return;
        if (info.visibleFraction == 1) {
          setState(() {
            isVisiable = true;
            _controller.play();
          });
        }
        if (info.visibleFraction == 0) {
          setState(() {
            isVisiable = false;
            _controller.pause();
          });
        }
      },
      child: Scaffold(
        appBar: AppBar(title: Text('the NO.${widget.index} page')),
        body: Center(
          child: _controller.value.isInitialized
              ? AspectRatio(
                  aspectRatio: _controller.value.aspectRatio,
                  child: VideoPlayer(_controller),
                )
              : const CircularProgressIndicator(),
        ),
      ),
    );
  }
}
